<link href="__PUBLIC__/vendors/jquery-contextMenu/dist/jquery.contextMenu.min.css" rel="stylesheet">
<link href="__PUBLIC__/vendors/jpicker/jPicker.css" rel="stylesheet">
<link href="__PUBLIC__/vendors/jpicker/css/jPicker-1.1.6.min.css" rel="stylesheet">
<style type="text/css">
    #poster
    {
        width: 320px;
        height: 504px;
        background-color: #00a0e9;
        display: inline-block;
    }
    .operation-panel
    {
        display: inline-block;
        height: 504px;
        width: 100%;
    }
    #poster .bg {width:100%;z-index:0}
    #poster .drag[type=nickname] { width:80px;height:40px; font-size:16px; font-family: 黑体;}
    #poster .drag[type=qr] { width:100px;height:100px;}
    #poster .drag[type=avatar] { width:80px;height:80px;}
    #poster .drag img
    {
        z-index: 0;
        width: 100%;
    }

    #poster .rRightDown,.rLeftDown,.rLeftUp,.rRightUp,.rRight,.rLeft,.rUp,.rDown{
        position:absolute;
        width:7px;
        height:7px;
        z-index:1;
        font-size:0;
    }

    #poster .rRightDown,.rLeftDown,.rLeftUp,.rRightUp,.rRight,.rLeft,.rUp,.rDown{
        background:#C00;
    }
    .rLeftDown,.rRightUp{cursor:ne-resize;}
    .rRightDown,.rLeftUp{cursor:nw-resize;}
    .rRight,.rLeft{cursor:e-resize;}
    .rUp,.rDown{cursor:n-resize;}
    .rLeftDown{left:-4px;bottom:-4px;}
    .rRightUp{right:-4px;top:-4px;}
    .rRightDown{right:-4px;bottom:-4px;}
    .rRightDown{background-color:#00F;}

    .rLeftUp{left:-4px;top:-4px;}
    .rRight{right:-4px;top:50%;margin-top:-4px;}
    .rLeft{left:-4px;top:50%;margin-top:-4px;}
    .rUp{top:-4px;left:50%;margin-left:-4px;}
    .rDown{bottom:-4px;left:50%;margin-left:-4px;}

    .input-group-addon .jPicker
    {
        display: inline-block;
        height: 32px;
        width: 100%;
    }
    .input-group-addon .jPicker .Icon
    {
        height: 100%;
        width: 100%;
    }
    .input-group-addon .jPicker .Icon .Image
    {
        background: none !important;
    }
    .qr-code
    {
        border: 1px solid #000000;
        background-color: #9B59B6;
        min-height: 100px;
        min-width: 100px;
    }
    .select2-container
    {
        width: 100% !important;
    }
</style>
<form class="form-horizontal">
    <!--海报内容-->
    <div class="col-xs-5" style="text-align: right;">
        <div id="poster">
            {if condition="$settings"}
            <!--背景图-->
            {php}$background = $settings["background"];unset($settings["background"]);{/php}

            {volist name="settings" id="item" key="key"}
                <div class="drag" type="{$item.type}" index="{php} echo $key+1{/php}"
                     style="zindex:{php echo $key+1};left:{$item.left};top:{$item.top};
                                 width:{$item.width};height:{$item.height}" size="{$item.size}" color="{$item.color}">
                    {if condition="$item.type=='qr'"}
                        <img src="__PUBLIC__images/qr.png" />
                    {elseif condition="$item.type=='avatar'"}
                        <img src="__PUBLIC__images/default_icon.png" />
                    {elseif condition="$item.type=='nickname'"}
                        <div class=text style="font-size:{$item.size};color:{$item.color}">
                            昵称
                        </div>
                    {/if}
                    <div class="rRightDown"> </div>
                    <div class="rLeftDown"> </div>
                    <div class="rRightUp"> </div>
                    <div class="rLeftUp"> </div>
                    <div class="rRight"> </div>
                    <div class="rLeft"> </div>
                    <div class="rUp"> </div>
                    <div class="rDown"></div>
                </div>
            {/volist}

            <!--背景图-->
            <img src="{$background}" id="poster-background" class="bg">
            {else/}
            <img src="" id="poster-background" class="bg">
            {/if}

        </div>
    </div>
    <div class="col-xs-7">
        <div class="panel panel-default operation-panel">
            <div class='panel-body'>
                <div class="form-group" id="bgset">
                    <label class="col-sm-2 control-label">
                        <?php echo translate("poster-spread:background"); ?>
                    </label>
                    <div class="col-sm-9 col-xs-12">

                        <input id="single-uploader-poster" name="single-uploader-poster" type="file" class="file-loading">
                        <input type="hidden" id="poster-picker" name="poster-picker">
                        <span class='help-block'>
                            <?php echo translate("poster-spread:background_desc"); ?>
                        </span>
                    </div>


                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">
                        <?php echo translate("poster-spread:poster_element"); ?>
                    </label>
                    <div class="col-sm-9 col-xs-12">
                        <button class='btn btn-default btn-element' type='button' data-type='avatar' >
                            <?php echo translate("poster-spread:avatar_btn"); ?>
                        </button>
                        <button class='btn btn-default btn-element' type='button' data-type='nickname' >
                            <?php echo translate("poster-spread:nickname_btn"); ?>
                        </button>
                        <button class='btn btn-default btn-element' type='button' data-type='qr' >
                            <?php echo translate("poster-spread:qr_btn"); ?>
                        </button>
                    </div>
                </div>
                <div id='qr-container' style='display:none'>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">
                            <?php echo translate("poster-spread:qr_size"); ?>
                        </label>
                        <div class="col-sm-9 col-xs-12">
                            <select id='qrsize' class='form-control'>
                                <option value='1'>1</option>
                                <option value='2'>2</option>
                                <option value='3'>3</option>
                                <option value='4'>4</option>
                                <option value='5'>5</option>
                                <option value='6'>6</option>
                            </select>
                        </div>

                    </div>
                </div>

                <div id='nickname-container' style='display:none'>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">昵称颜色</label>
                        <div class="col-sm-9 col-xs-12">
                            <div class="input-group">
                                <input type="text" class="form-control" id="nickname-color" placeholder="Amount">
                                <div class="input-group-addon" style="padding: 0; width: 30px;">
                                    <div id="color-picker"></div>
                                </div>
                            </div>

                        </div>

                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">昵称大小</label>
                        <div class="col-sm-4">
                            <div class='input-group'>
                                <input type="text" id="namesize" class="form-control namesize" placeholder="例如: 14,16"  />
                                <div class='input-group-addon'>px</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-xs-2 control-label"></label>
                    <div class="col-xs-4">
                        <button type="button" class="btn btn-success btn-block" onclick="submitPoster(this)">
                            <?php echo translate("poster:submit"); ?>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

<!-- PREVIEW DATA -->
<link href="__PUBLIC__/vendors/bootstrap-fileinput/css/fileinput.min.css" rel="stylesheet">
<!-- load the JS files in the right order -->
<!-- sortable plugin for sorting/rearranging initial preview -->
<script src="__PUBLIC__/vendors/bootstrap-fileinput/js/plugins/sortable.min.js"></script>
<!-- purify plugin for safe rendering HTML content in preview -->
<script src="__PUBLIC__/vendors/bootstrap-fileinput/js/plugins/purify.min.js"></script>
<script src="__PUBLIC__/vendors/bootstrap-fileinput/js/fileinput.js"></script>
<script src="__PUBLIC__/vendors/bootstrap-fileinput/js/zh.js"></script>


<script>
    //上传处理器
    var input= $("#single-uploader-poster");

    //图片管理器
    var image = $("#poster-picker");
    input.fileinput({
        language: 'zh',
        uploadUrl: "{:url('Utils/uploadSingleImage',array('name'=>'single-uploader-poster'))}",
        uploadAsync: true,
        maxFileCount: 1,
        showPreview: false,
        showUpload: false,
        showRemove: false,
        overwriteInitial: true,
        autoReplace: true,
        maxFileSize: 1024,
        layoutTemplates: {actionZoom:"",actionUpload:"",actionDelete:"",progress:""},
        purifyHtml: true,
        uploadExtraData: {
            img_key: "1000",
            img_keywords: "happy, places",
        }
    }).on("filebatchselected", function(event, files) {
        $(".file-preview-success").remove();
        if (files.length > 0)
        {
            //图片选择完成后自动上传
            input.fileinput("upload");
        }
    }).on('fileuploaded', function(event, data, id) {
        if(data.response)
        {
            if (data.response.status == 0)
            {
                //获取图像URL
                var url = data.response.url;

                image.val(url);

                $("#poster-background").attr("src", url);
            }
        }
    }).on('fileclear', function(event, id) {
        image.val("");
    }).on('filesuccessremove', function(e, id) {
        image.val("");
    }).on('filedeleted', function(e, id) {
        console.log('File uploaded params', id);
        image.val("");
    });

</script>


<script src="__PUBLIC__/vendors/jpicker/jpicker-1.1.6.min.js"></script>
<script src="__PUBLIC__/js/designer.js"></script>
<script src="__PUBLIC__/vendors/jquery-contextMenu/dist/jquery.contextMenu.min.js"></script>
<script src="__PUBLIC__/vendors/select2/js/select2.min.js"></script>

<script type="application/javascript">

    //是否正在提交
    var isSubmitting = false;

    //提交海报设置
    function submitPoster(obj)
    {
        //如果正在提交，则不执行任何操作
        if (isSubmitting)
        {
            return;
        }

        //背景图
        var background = $("#poster-background");

        //判断是否上传背景图
        if (background.attr("src").length == 0)
        {
            showErrorMessage("<?php echo translate('poster-spread:empty_background'); ?>");
            return;
        }

        //数据
        var data = {background: background.attr("src")};
        $('.drag').each(function(){
            var obj = $(this);
            var type = obj.attr('type');
            var left = obj.css('left'),top = obj.css('top');
            var d= {left:left,top:top,type:obj.attr('type'),width:obj.css('width'),height:obj.css('height')};

            //昵称
            if(type=='nickname')
            {
                d.size = obj.attr('size');
                d.color = obj.attr('color');

                data.nickname = d;
            }
            else if(type=='qr')
            {
                d.size = obj.attr('size');
                d.color = 0;
                data.qr = d;
            }
            else if(type=='avatar')
            {
                d.size = 0;
                d.color = 0;
                data.avatar = d;
            }
        });

        console.log(data);

        isSubmitting = true;

        $.ajax({
            url: "",
            type: "POST",
            dataType: "JSON",
            data: data,
            success: function (json) {
                if (json.status == 0)
                {
                    location.reload(true);
                }
                else
                {
                    showErrorMessage(json.info);
                }

                //完成提交
                isSubmitting = false;
            }
        })
    }

    //绑定事件
    function bindEvents(obj){

        var index = obj.attr('index');

        var rs = new Resize(obj, { Max: true, mxContainer: "#poster" });
        rs.Set($(".rRightDown",obj), "right-down");
        rs.Set($(".rLeftDown",obj), "left-down");
        rs.Set($(".rRightUp",obj), "right-up");
        rs.Set($(".rLeftUp",obj), "left-up");
        rs.Set($(".rRight",obj), "right");
        rs.Set($(".rLeft",obj), "left");
        rs.Set($(".rUp",obj), "up");
        rs.Set($(".rDown",obj), "down");
        rs.Scale = true;

        //获取类型
        var type = obj.attr('type');
        //若为昵称，则禁用等比例缩放
        if(type == "nickname")
        {
            rs.Scale = false;
        }

        //创建拖拽器
        new Drag(obj, {
            Limit: true,
            mxContainer: "#poster"
        });

        //移除拖拽器
        $(".drag .remove").unbind("click").click(function(){
            $(this).parent().remove();
        });

        $.contextMenu({
            selector: '.drag[index=' + index + ']',
            callback: function(key, options) {
                var index = parseInt($(this).attr('zindex'));

                if(key=='next'){
                    var nextdiv = $(this).next('.drag');
                    if(nextdiv.length>0 ){
                        nextdiv.insertBefore($(this));
                    }
                } else if(key=='prev'){
                    var prevdiv = $(this).prev('.drag');
                    if(prevdiv.length>0 ){
                        $(this).insertBefore(prevdiv);
                    }
                } else if(key=='last'){
                    var len = $('.drag').length;
                    if(index >=len-1){
                        return;
                    }
                    var last = $('#poster .drag:last');
                    if(last.length>0){
                        $(this).insertAfter(last);
                    }
                }else if(key=='first'){
                    var index = $(this).index();
                    if(index<=1){
                        return;
                    }
                    var first = $('#poster .drag:first');
                    if(first.length>0){
                        $(this).insertBefore(first);
                    }
                }else if(key=='delete'){
                    $(this).remove();
                }
                var n =1 ;
                $('.drag').each(function(){
                    $(this).css("z-index",n);
                    n++;
                })
            },
            items: {
                "next": {name: "<?php echo translate('poster-spread:move_next'); ?>"},
                "prev": {name: "<?php echo translate('poster-spread:move_prev'); ?>"},
                "last": {name: "<?php echo translate('poster-spread:move_last'); ?>"},
                "first": {name: "<?php echo translate('poster-spread:move_first'); ?>"},
                "delete": {name: "<?php echo translate('poster-spread:delete'); ?>"}
            }
        });
        obj.unbind('click').click(function(){
            bind($(this));
        })
    }

    //默认昵称颜色
    var nicknameColor = "#C8161D";
    //昵称更新计时器
    var nicknameTimer = 0;
    
    //隐藏所有设置容器
    function hideContainer()
    {
        //隐藏二维码
        $("#qr-container").hide();

        //隐藏昵称
        $("#nickname-container").hide();
        //清除计时器
        clearInterval(nicknameTimer);
    }

    function bind(obj){
        //隐藏设置容器
        hideContainer();

        var type = obj.attr('type');

        if(type=='nickname')
        {
            //昵称容器
            var nicknameContainer = $("#nickname-container");

            //显示容器
            nicknameContainer.show();

            //字体颜色
            var color = obj.attr('color') || nicknameColor;
            //字体大小
            var size = obj.attr('size') || "16";
            var input = nicknameContainer.find('input:first');
            var namesize = nicknameContainer.find('#namesize');
            var picker = nicknameContainer.find('.sp-preview-inner');
            input.val(color);
            namesize.val(size.replace("px",""));
            picker.css( {'background-color':color,'font-size':size});

            //使用计时器更新
            nicknameTimer = setInterval(function(){
                obj.attr('color',input.val()).find('.text').css('color',input.val());
                obj.attr('size',namesize.val() +"px").find('.text').css('font-size',namesize.val() +"px");
            },10);

        } else if(type=='qr')
        {
            //获取容器
            var qrContainer = $("#qr-container");

            //显示容器
            qrContainer.show();
            var size = obj.attr('size') || "3";
            var sel = qrContainer.find('#qrsize');
            sel.val(size);
            sel.unbind('change').change(function(){
                obj.attr('size',sel.val())
            });
        }
    }

    $(function() {

        //初始化颜色选择器
        $("#color-picker").jPicker({
            window: {
                expandable: true,
                position: {
                    y: "60px"
                }
            },
            color: {
                active: new $.jPicker.Color({ ahex: nicknameColor})
            },
            images: {
                clientPath: "__PUBLIC__/vendors/jpicker/images/"
            }
        }, function (color, content) {
            var all = color.val('all');
            $("#nickname-color").val("#" + all.hex);
        });

        //获取分类
        $("#qrsize").select2({
            placeholder: "<?php echo translate('poster-spread:qr_size_selector'); ?>",
            allowClear: true
        });

        //绑定拖拽元素
        $(".drag").each(function(){
            bindEvents($(this));
        });

        //添加元素
        $(".btn-element").click(function(){

            hideContainer();

            //背景图
            var background = $("#poster-background");

            //判断是否选择背景图
            if (background.attr("src").length == 0)
            {
                showErrorMessage("<?php echo translate('poster-spread:empty_background'); ?>");
                return;
            }

            //按钮操作的数据类型
            var type = $(this).data('type');

            //元素数组
            var elementArray = $(".drag[type='" + type + "']");

            var element = "";
            //二维码
            if(type=='qr')
            {
                //判断二维码是否存在
                if (elementArray.length > 0)
                {
                    showErrorMessage("<?php echo translate('poster-spread:qr_exist'); ?>");
                    return;
                }

                element = '<img src="__PUBLIC__images/qr.png" />';
            }
            //头像
            else if(type=="avatar")
            {
                //判断头像是否存在
                if (elementArray.length > 0)
                {
                    showErrorMessage("<?php echo translate('poster-spread:avatar_exist'); ?>");
                    return;
                }

                element = '<img src="__PUBLIC__images/default_icon.png" />';
            }
            //昵称
            else if(type=='nickname')
            {
                //判断昵称是否存在
                if (elementArray.length > 0)
                {
                    showErrorMessage("<?php echo translate('poster-spread:nickname_exist'); ?>");
                    return;
                }

                element = "<div class='text'><?php echo translate('poster-spread:nickname'); ?></div>";
            }
            var index = $("#poster .drag").length+1;
            var obj = $('<div class="drag" type="' + type +'" index="' + index +'" style="z-index:' + index+'">' + element+'<div class="rRightDown"> </div><div class="rLeftDown"> </div><div class="rRightUp"> </div><div class="rLeftUp"> </div><div class="rRight"> </div><div class="rLeft"> </div><div class="rUp"> </div><div class="rDown"></div></div>');

            //昵称
            if (type == "nickname")
            {
                obj.attr("size", "16px");
                obj.attr("color", nicknameColor);
            }
            //二维码
            else if (type == "qr")
            {
                obj.attr("size", 1);
            }
            obj.insertBefore(background);

//            $('#poster').insertBefore(obj);

            bindEvents(obj);

        });

    });
</script>